/**
 * Created by wry on 2014/12/22.
 */
var amqp = require('amqp');
var toolUtil = require('../common/utils/toolUtil');
var qiniuUtil = require('../common/utils/qiniuUtil');
var shortMessage = mongoose.model('system_codeShortMessage');
var loginOrRegisterLog = mongoose.model('system_loginOrRegisterLog');
var Users = mongoose.model('user');
var pushRecords = mongoose.model('system_operateMessages_log');
var operateMessage = mongoose.model('system_operateMessages');
var moment = require('moment');
var async = require('async');
var cacheUtil = require('../common/utils/cacheUtil');
var SystemMessage = mongoose.model('system_messages');
var http = require('http');
var mysqlUtil = require('../common/utils/mysqlUtil');


global.mqConnection = amqp.createConnection(rabbitMqOpt);


// Wait for connection to become established.
mqConnection.on('ready', function () {

    logger.info('mqConnection is ready');

    var exchange = mqConnection.exchange('ex.push', {type: 'direct', durable: true, autoDelete: false});
    exchange.on('open', function () {
        logger.info('Exchange ' + exchange.name + ' is open');
    });

    global.auditEx = mqConnection.exchange('ex.audit', {type: 'fanout', durable: true, autoDelete: false});

    auditEx.on('open', function () {
        logger.info('Exchange ' + auditEx.name + ' is open');
    });

    mqConnection.queue('verificationCodeMessage', function (q) {
        //Catch all messages
        q.bind('#');
        //Receive messages
        q.subscribe(function (message) {
            logger.debug(message);

            var msg = '您的验证码为：' + message.verificationCode + '。该验证码10分钟内有效，请在页面中输入以完成验证。';

            var data = {
                "phoneNum": message.mobilePhone,
                "content": msg,
                "type": message.type,
                "smsType": 1
            };

            mqConnection.publish('q.msg.publish', data);
            /*  宝宝树66小区二次改造    add 短信两次修正  llh  20170822   start   */
            // msg = encodeURIComponent(msg);

            /*  宝宝树66小区二次改造    add   llh  20170721   start   */
            // var url = "http://175.25.18.221:8087/MWGate/wmgw.asmx/MongateCsSpSendSmsNew?"
            //     +"userId="+spid+"&password="+sppassword+"&pszMobis="+message.mobilePhone+"&pszMsg="+msg+"&iMobiCount="+1;
            //
            // restClient.get(url, function (data, response) {
            //     logger.info(data);
            //     if (response.statusCode = '200') {
            //         //var result = data.split('&');
            //
            //         var temp = new shortMessage();
            //         temp.deviceId = message.deviceId;
            //         temp.mobilePhone = message.mobilePhone;
            //         temp.verificationCode = message.verificationCode;
            //         //temp.messageId = result[2].split('=')[1];
            //         //temp.status = result[3].split('=')[1];
            //         //temp.errCode = result[4].split('=')[1];
            //         temp.save();
            //     }
            // }).on('error', function (err) {
            //     logger.error('set message to esmsl went wrong on the request' + err);
            // });
            /*  宝宝树66小区二次改造    add   llh  20170721   end   */
            /*  宝宝树66小区二次改造    add 短信两次修正  llh  20170822   end   */
            // restClient.get('http://esms1.etonenet.com/sms/mt?command=MT_REQUEST&spid='
            //     + spid + '&sppassword=' + sppassword
            //     + '&da=86' + message.mobilePhone + '&dc=8&sm=' + msg, function (data, response) {
            //     logger.info(data);
            //     if (response.statusCode = '200') {
            //         var result = data.split('&');
            //
            //        var temp = new shortMessage();
            //        temp.deviceId = message.deviceId;
            //        temp.mobilePhone = message.mobilePhone;
            //        temp.verificationCode = message.verificationCode;
            //        temp.messageId = result[2].split('=')[1];
            //        temp.status = result[3].split('=')[1];
            //        temp.errCode = result[4].split('=')[1];
            //        temp.save();
            //    }
            //}).on('error', function (err) {
            //    logger.error('set message to esmsl went wrong on the request' + err);
            //});

            // restClient.get('http://esms1.etonenet.com/sms/mt?command=MT_REQUEST&spid='
            //     + spid + '&sppassword=' + sppassword
            //     + '&da=86' + message.mobilePhone + '&dc=8&sm=' + msg, function (data, response) {
            //     logger.info(data);
            //     if (response.statusCode = '200') {
            //         var result = data.split('&');
            //
            //         var temp = new shortMessage();
            //         temp.deviceId = message.deviceId;
            //         temp.mobilePhone = message.mobilePhone;
            //         temp.verificationCode = message.verificationCode;
            //         temp.messageId = result[2].split('=')[1];
            //         temp.status = result[3].split('=')[1];
            //         temp.errCode = result[4].split('=')[1];
            //         temp.save();
            //     }
            // }).on('error', function (err) {
            //     logger.error('set message to esmsl went wrong on the request' + err);
            // });

        });
    });


    mqConnection.queue('q.log.loginOrRegister', function (q) {
        //Catch all messages
        q.bind('#');
        //Receive messages
        q.subscribe(function (message) {
            new loginOrRegisterLog(message).save();
        });
    });

    mqConnection.queue('getuiPushMessage', function (q) {
        q.bind('#');
        //Receive messages
        q.subscribe(function (message) {

            var messageType = 1;  //1,邻里通知 2，

            logger.info('getui---');
            logger.info(message);

            var ContentAvailable = '';

            if (message.type == 'operate') {
                var temp = new pushRecords();
                temp.title = message.content.desc;
                temp.contentId = message.content.contentId;
                temp.openType = message.content.openType;
                temp.url = message.content.url;
                temp.save(function (err, result) {
                    ContentAvailable = "1";

                    messageType = 2;
                    if (message.content.contentId == '563b260e30644f2d6f203280') {
                        message.content.url = 'http://h5.66xiaoqu.com/app/video/insite_t.html'
                    }

                    getuiPush(message, exchange, ContentAvailable, messageType, result._id);
                });
            } else {
                getuiPush(message, exchange, ContentAvailable, messageType);
            }

        });
    });

    mqConnection.queue('q.push.transmission', function (q) {
        //Catch all messages
        q.bind('#');
        //Receive messages
        q.subscribe(function (message) {
            var uList = [];

            console.log('q.push.transmission');

            async.each(message.uList, function (userId, callback) {
                Users.findOne({_id: userId}, 'clientId', function (err, result) {
                    if (result.clientId != null) {
                        uList.push(result.clientId);
                    }
                    callback();
                });
            }, function (err) {
                if (uList.length > 0) {
                    var tPushData = {
                        targetUser: 3,
                        targetPlatform: 1,
                        tags: [],
                        users: uList,
                        message: "",
                        transmissionContent: message.content,
                        transmissionType: 2,
                        actionLocKey: "",
                        badge: 1,
                        sound: "default",
                        payload: "",
                        locKey: "",
                        locArgs: "",
                        launchImage: "",
                        ContentAvailable: "",
                        pushApns: 'no',
                        messageType: 1
                    };
                    //mqConnection.publish('q.push.info', tPushData);
                    exchange.publish('r.push', tPushData);
                }
            });
        });
    });

    mqConnection.queue('q.push.tag', function (q) {
        //Catch all messages
        q.bind('#');
        //Receive messages
        q.subscribe(function (message) {

            logger.debug('q.push.tag-----success');

            var tPushData = {
                targetUser: 2,
                targetPlatform: 1,
                tags: message.tags,
                users: [],
                message: "",
                transmissionContent: message.content,
                transmissionType: 2,
                actionLocKey: "",
                badge: -1,
                sound: "default",
                payload: "",
                locKey: "",
                locArgs: "",
                launchImage: "",
                ContentAvailable: "",
                pushApns: message.pushApns,
                messageType: 2
            };
            //mqConnection.publish('q.push.info', tPushData);
            exchange.publish('r.push', tPushData);
        });
    });


    //第三方登陆头像上传替换
    mqConnection.queue('q.thirdParty.image', function (q) {
        //Catch all messages
        q.bind('#');
        //Receive messages
        q.subscribe(function (message) {

            logger.debug('q.thirdParty.image---' + message);


            http.request(message.image, function (response) {
                var imagedata = '';
                response.setEncoding('binary');
                response.on('data', function (chunk) {
                    imagedata += chunk
                });

                response.on('end', function () {

                    var buffer = new Buffer(imagedata, "binary");

                    qiniuUtil.uploadBuf(buffer, function (err, image) {
                        if (image != null) {
                            Users.update({_id: message.user}, {images: [{imageURL: image}]}).exec();
                        }
                    });
                });
            }).end();
        });
    });


    //app请求状态记录
    mqConnection.queue('q.app.request:log', function (q) {
        //Catch all messages
        q.bind('#');
        //Receive messages
        q.subscribe(function (message) {

            var str = message.serviceCode + '';

            if (message.httpStatus == 200) {
                var code = Number(str.substr(0, 4));
                var time = Number(str.substr(4, 3)) * 1000 + Number(str.substr(7, 2)) * 10;
            }

            var data = {
                user_id: message.userId,
                service_code: code,
                service_name: SERVICE_MAP[code],
                url: message.url,
                method: message.method,
                http_status: message.httpStatus,
                status: message.status,
                message: message.message,
                time: message.time,
                node_time: time,
                net_type: message.netType,
                net_provider: message.netProvider,
                lat: message.lat,
                lng: message.lng,
                address: message.address,
                device_id: message.deviceId,
                type: message.type,
                vname: message.vname,
                vcode: message.vcode,
                channelId: message.channelId,
                create_time: new Date().getTime()
            };
            /*  宝宝树66小区二次改造    del   dayu  20170723   start   */
            /*mysqlUtil.logQuery('insert into app_request_log set?', data, function (err, result) {
                if (err) logger.error(err.message);
            })*/
            /*  宝宝树66小区二次改造    del   dayu  20170723   end   */
        });
    });
});


function getuiPush(message, exchange, ContentAvailable, messageType, recordId) {

    var uList = [];
    var tList = [];
    var badgeUsers = [];

    message.content.contentId = message.content.contentId ? message.content.contentId : new Date().getTime() + '';

    async.each(message.uList, function (userId, callback) {
        Users.findOne({_id: userId}, 'clientId appSetting community', function (err, result) {
            var setting;
            if (result != null) {
                setting = result.appSetting;

                if (message.type == 'operate') {
                    var temp = new operateMessage();
                    temp.user = userId;
                    temp.message = message.content.desc;
                    temp.messageId = message.content.contentId;
                    temp.createdBy = message.content.createdBy;
                    temp.url = message.content.url;
                    temp.pushLogId = recordId;
                    temp.openType = message.content.openType;
                    temp.toCommunity = result.community;
                    temp.tag = message.tag;
                    temp.save();
                }
            }
            if (result != null && result.clientId != null) {
                if (setting == null || setting.notDisturb == null || setting.notDisturb.on == false
                    || setting.notDisturb.startTime == null || setting.notDisturb.endTime == null
                    || !toolUtil.time_range(setting.notDisturb.startTime, setting.notDisturb.endTime)) {

                    uList.push(result.clientId);

                    var userT = {
                        userId: userId,
                        clientId: result.clientId
                    };

                    badgeUsers.push(userT)
                } else {
                    tList.push(result.clientId);
                }
            }
            callback();
        });
    }, function (err) {
        if (err) {
            logger.info("getui---error---" + err.message);
        } else {

            if (recordId != null) {
                redisClient.hset('system_operate_message:contentId:' + recordId, 'targetPushCount', uList.length + tList.length);
            }

            var payload = {
                ot: message.content.openType,
                f: message.content.flag,
                url: message.content.url,
                t: message.content.type,
                q: message.content.contentId,
                by: message.content.createdBy
            };


            if (uList.length > 0) {

                var content = {
                    ot: message.content.openType,
                    f: message.content.flag,
                    t: message.content.type,
                    url: message.content.url,
                    q: message.content.contentId,
                    by: message.content.createdBy,
                    ds: message.content.desc
                };

                if (message.type == 'operate') {
                    var pushData = {
                        targetUser: 3,
                        targetPlatform: 1,
                        tags: [],
                        users: uList,
                        message: message.content.desc,
                        transmissionContent: content,
                        transmissionType: 2,
                        actionLocKey: "",
                        badge: -1,
                        sound: "default",
                        payload: payload,
                        locKey: "",
                        locArgs: "",
                        launchImage: "",
                        ContentAvailable: ContentAvailable,
                        pushApns: 'yes',
                        msgType: messageType,
                        objId: recordId
                    };
                    //mqConnection.publish('q.push.info', pushData);
                    exchange.publish('r.push', pushData);
                } else {
                    //badgeUsers.forEach(function (userId) {
                    //    SystemMessage.count({toUser: userId, readFlag: false}, function (err, count) {
                    //
                    //    })
                    //})

                    logger.info('push--success');


                    var pushData = {
                        targetUser: 3,
                        targetPlatform: 1,
                        tags: [],
                        users: uList,
                        message: message.content.desc,
                        transmissionContent: content,
                        transmissionType: 2,
                        actionLocKey: "",
                        badge: 1,
                        sound: "default",
                        payload: payload,
                        locKey: "",
                        locArgs: "",
                        launchImage: "",
                        ContentAvailable: ContentAvailable,
                        pushApns: message.pushApns ? message.pushApns : 'yes',
                        msgType: messageType
                    };
                    //mqConnection.publish('q.push.info', pushData);
                    exchange.publish('r.push', pushData);
                }
            }

            if (tList.length > 0) {

                var content = {
                    ot: message.content.openType,
                    f: message.content.flag,
                    t: 2,
                    url: message.content.url,
                    q: message.content.contentId,
                    by: message.content.createdBy,
                    ds: message.content.desc
                };

                var tPushData = {
                    targetUser: 3,
                    targetPlatform: 1,
                    tags: [],
                    users: tList,
                    message: message.content.desc,
                    transmissionContent: content,
                    transmissionType: 2,
                    actionLocKey: "",
                    badge: 1,
                    sound: "default",
                    payload: payload,
                    locKey: "",
                    locArgs: "",
                    launchImage: "",
                    ContentAvailable: ContentAvailable,
                    pushApns: 'no',
                    msgType: messageType,
                    objId: recordId
                };
                //mqConnection.publish('q.push.info', tPushData);
                exchange.publish('r.push', tPushData);
            }
        }
    });
}
